<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\TradeOffline as TradeOfflineModel;
use app\common\model\TradeOfflineOrder;
use app\common\tool\Result;
use think\exception\ValidateException;
use think\Response;

class TradeOffline extends Base
{
    public function index(): Response
    {
        $result['account'] = [
            'title' => get_pay_way('usdt'),
            'type' => 'usdt',
            'balance' => $this->user->assets->usdt
        ];
        $method = [];
        if (!empty($this->system['draw_bank_open'])) {
            $method[] = [
                'title' => get_pay_way('bank'),
                'type' => 'bank',
                'icon' => '/static/admin/img/bank.png'
            ];
        }
        if (!empty($this->system['draw_wechat_open'])) {
            $method[] = [
                'title' => get_pay_way('wechat'),
                'type' => 'wechat',
                'icon' => '/static/admin/img/wechat.png'
            ];
        }
        if (!empty($this->system['draw_alipay_open'])) {
            $method[] = [
                'title' => get_pay_way('alipay'),
                'type' => 'alipay',
                'icon' => '/static/admin/img/alipay.png'
            ];
        }
        if (!empty($this->system['draw_usdt_open'])) {
            $method[] = [
                'title' => get_pay_way('usdt'),
                'type' => 'usdt',
                'icon' => '/static/admin/img/usdt.png'
            ];
        }
        $result['method'] = $method;
        $result['type'] = [
            [
                'id' => 1,
                'title' => getTradeType(1)
            ],
            [
                'id' => 2,
                'title' => getTradeType(2)
            ]
        ];
        $result['factor'] = [
            'price' => $this->system['usdt_price'],
            'trade_open' => $this->system['trade_offline_open'],
            'trade_publish_min' => $this->system['trade_offline_publish_min'],
            'trade_publish_bs' => $this->system['trade_offline_publish_bs'],
            'trade_min' => $this->system['trade_offline_min'],
            'trade_bs' => $this->system['trade_offline_bs'],
            'trade_cost' => $this->system['trade_offline_cost'],
            'trade_pay_timeout' => $this->system['trade_offline_pay_timeout'],
            'trade_auto_receipt_time' => $this->system['trade_offline_auto_receipt_time']
        ];

        return Result::success('success', $result);
    }

    public function hallList(): Response
    {
        $param = $this->request->get();
        $map['status'] = 1;
        if (!empty($param['type'])) {
            $map['type_id'] = $param['type'];
        }
        $result = TradeOfflineModel::getPageList($map,
            'id,type_id,amount,surplus_amount as amount,price,method,create_time',
            $this->getPage(), $this->getLimit(), false, [], [], [], [], [], '', ['type_name']);
        foreach ($result['data'] as &$item) {
            $item->merit = round($item->amount * $item->price, 2);
            $methodList = explode(',', $item->method);
            $method = [];
            foreach ($methodList as $value) {
                $method[] = [
                    'title' => get_pay_way($value),
                    'type' => $value,
                    'icon' => "/static/admin/img/{$value}.png"
                ];
            }
            $item->method = $method;
        }

        return Result::fastReturn($result);
    }

    public function save(): Response
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'TradeOffline');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }

        return Result::fastReturn(TradeOfflineModel::add($param, $this->user, $this->system));
    }

    public function record(): Response
    {
        $param = $this->request->get();
        $map['uid'] = $this->user->id;
        if (!empty($param['type'])) {
            $map['type_id'] = $param['type'];
        }
        if (!empty($param['status'])) {
            $map['status'] = $param['status'];
        }
        $result = TradeOfflineModel::getPageList($map,
            'id,type_id,sn,account,amount,surplus_amount,price,method,status,finish_time,cancel_time,create_time',
            $this->getPage(), $this->getLimit(), false, [], [], [], [], [], '', ['type_name', 'status_name']);
        foreach ($result['data'] as &$item) {
            $item->total_merit = round($item->amount * $item->price, 2);
            $item->surplus_merit = round($item->surplus_amount * $item->price, 2);
            $methodList = explode(',', $item->method);
            $method = [];
            foreach ($methodList as $value) {
                $method[] = [
                    'title' => get_pay_way($value),
                    'type' => $value,
                    'icon' => "/static/admin/img/{$value}.png"
                ];
            }
            $item->method = $method;
        }

        return Result::fastReturn($result);
    }

    public function revoke(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn(TradeOfflineModel::revoke($param, $this->user));
    }

    public function add(): Response
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'TradeOfflineOrder.add');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }

        return Result::fastReturn(TradeOfflineOrder::add($param, $this->user, $this->system));
    }

    public function myBuy(): Response
    {
        $param = $this->request->get();
        $map['buyer_id'] = $this->user->id;
        if (!empty($param['status'])) {
            $map['status'] = $param['status'];
        }
        $result = TradeOfflineOrder::getPageList($map,
            'id,sn,seller_id,account,amount,price,real_amount,status,create_time',
            $this->getPage(), $this->getLimit(), false, ['seller'], [], [], [], [], '', ['status_name']);
        foreach ($result['data'] as &$item) {
            $item->seller = [
                'id' => $item->seller->id,
                'code' => $item->seller->code,
                'nickname' => $item->seller->nickname,
                'mobile' => $item->seller->mobile,
                'photo' => $item->seller->photo
            ];
        }

        return Result::fastReturn($result);
    }

    public function buyInfo($id): Response
    {
        $info = TradeOfflineOrder::with(['trade', 'seller'])
            ->withoutField('buyer_id,cost_rate,admin_id,admin_name,update_time,delete_time')
            ->where(['id' => $id, 'buyer_id' => $this->user->id])->append(['method_name', 'status_name'])->find();
        if (empty($info)) return Result::fail('买单不存在');
        if ($info->status == 1) {
            $info->surplus_time = round(($info->expire_time - time()) * 1000);
            $methodList = explode(',', $info->trade->method);
            $method = [];
            if (in_array('bank', $methodList) && !empty($info->seller->bank_number)) {
                $method[] = [
                    'title' => get_pay_way('bank'),
                    'type' => 'bank',
                    'icon' => '/static/admin/img/bank.png',
                    'bank_name' => $info->seller->bank_name,
                    'bank_open_name' => $info->seller->bank_open_name,
                    'bank_number' => $info->seller->bank_number,
                    'bank_address' => $info->seller->bank_address
                ];
            }
            if (in_array('wechat', $methodList) && !empty($info->seller->wechat_image)) {
                $method[] = [
                    'title' => get_pay_way('wechat'),
                    'type' => 'wechat',
                    'icon' => '/static/admin/img/wechat.png',
                    'wechat_name' => $info->seller->wechat_name,
                    'wechat_image' => $info->seller->wechat_image
                ];
            }
            if (in_array('alipay', $methodList) && !empty($info->seller->alipay_image)) {
                $method[] = [
                    'title' => get_pay_way('alipay'),
                    'type' => 'alipay',
                    'icon' => '/static/admin/img/alipay.png',
                    'alipay_name' => $info->seller->alipay_name,
                    'alipay_image' => $info->seller->alipay_image
                ];
            }
            if (in_array('usdt', $methodList) && !empty($info->seller->usdt_address)) {
                $method[] = [
                    'title' => get_pay_way('usdt'),
                    'type' => 'usdt',
                    'icon' => '/static/admin/img/usdt.png',
                    'usdt_type' => $info->seller->usdt_type,
                    'usdt_address' => $info->seller->usdt_address,
                    'usdt_image' => $info->seller->usdt_image
                ];
            }
            $info->methodList = $method;
            $info->method_icon = '';
        } elseif ($info->status == 2) {
            $info->surplus_time = round(($info->auto_receipt_time - time()) * 1000);
            $info->methodList = '';
            $info->method_icon = "/static/admin/img/{$info->method}.png";
        } else {
            $info->surplus_time = 0;
            $info->methodList = '';
            $info->method_icon = "/static/admin/img/{$info->method}.png";
        }
        $info->seller = [
            'id' => $info->seller->id,
            'code' => $info->seller->code,
            'nickname' => $info->seller->nickname,
            'mobile' => $info->seller->mobile,
            'photo' => $info->seller->photo
        ];
        unset($info->trade_id, $info->trade);

        return Result::success('success', $info);
    }

    public function mySell(): Response
    {
        $param = $this->request->get();
        $map['seller_id'] = $this->user->id;
        if (!empty($param['status'])) {
            $map['status'] = $param['status'];
        }

        return Result::fastReturn(TradeOfflineOrder::getPageList($map,
            'id,sn,buyer_id,account,amount,price,real_amount,status,create_time',
            $this->getPage(), $this->getLimit(), false, ['buyer'], [], [], [], [], '', ['status_name']));
    }

    public function sellInfo($id): Response
    {
        $info = TradeOfflineOrder::with(['buyer'])
            ->withoutField('trade_id,seller_id,cost_rate,admin_id,admin_name,update_time,delete_time')
            ->where(['id' => $id, 'seller_id' => $this->user->id])->append(['method_name', 'status_name'])->find();
        if (empty($info)) return Result::fail('卖单不存在');
        if ($info->status == 1) {
            $info->surplus_time = round(($info->expire_time - time()) * 1000);
            $info->method_icon = '';
        } elseif ($info->status == 2) {
            $info->surplus_time = round(($info->auto_receipt_time - time()) * 1000);
            $info->method_icon = "/static/admin/img/{$info->method}.png";
        } else {
            $info->surplus_time = 0;
            $info->method_icon = "/static/admin/img/{$info->method}.png";
        }

        return Result::success('success', $info);
    }

    public function payment(): Response
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'TradeOfflineOrder.payment');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }

        return Result::fastReturn(TradeOfflineOrder::confirmPayment($param, $this->user, $this->system));
    }

    public function receipt(): Response
    {
        $param = $this->request->post();

        return Result::fastReturn(TradeOfflineOrder::confirmReceipt($param, $this->user));
    }

    public function appeal(): Response
    {
        $param = $this->request->post();
        try {
            $this->validate($param, 'TradeOfflineOrder.appeal');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }

        return Result::fastReturn(TradeOfflineOrder::appeal($param, $this->user));
    }
}